<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="50">
        <el-col :span="4">
          <el-button type="primary" @click="showDialogVisible">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="roleslist"
      border
      stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- {{scope.row}}-->
            <el-row v-for="item in scope.row.children" :key="item.id" :gutter="50" class="elRow">
              <el-col :span="5" class="h-center">
                <el-tag effect="dark" @close="removeRightById(scope.row, item.id)" closable>
                  {{ item.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="item1 in item.children" :key="item1.id" class="elRow1">
                  <el-col :span="6" class="h-center">
                    <el-tag type="success" effect="dark" @close="removeRightById(scope.row, item1.id)" closable>
                      {{ item1.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18" class="h-center">
                    <el-tag v-for="item2 in item1.children" :key="item2.id" type="warning" class="tag-lv3" @close="removeRightById(scope.row, item2.id)" effect="dark" closable>
                      {{ item2.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="small" @click="showEditDialog(scope.row)">编剧</el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="rolesDeleted(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="small" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色的对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose">
      <!-- 内容主题区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色的对话框 -->
    <el-dialog
      title="角色修改"
      :visible.sync="editDialogVisible"
      width="50%">
      <!-- 内容主题区域 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose">
      <!-- 内容主题区域 -->
      <el-tree
        :data="rightslist"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        default-expand-all
        :default-checked-keys="defkeys"
        ref="treeref">
      </el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      roleslist: [],
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      rightslist: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点id值
      defkeys: [],
      // 当前即将分配权限的id
      roleId: '',
      addDialogVisible: false,
      editDialogVisible: false,
      setRightDialogVisible: false,
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入描述内容', trigger: 'blur' }
        ]
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入描述内容', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败 !')
      }
      // console.log(res.data[0])
      this.roleslist = res.data
    },
    addDialogClose() {
      this.$refs.addForm.resetFields()
    },
    showDialogVisible() {
      this.addDialogVisible = true
    },
    removeRightById(role, rightid) {
      // 根据id删除对应的权限
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightid}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        role.children = res.data
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    addRoles() {
      // 确定添加
      this.$refs.addForm.validate(async visible => {
        if (!visible) {
          this.$message.error('请输入完成的信息 !')
        } else {
          console.log(visible)
          const { data: res } = await this.$http.post('roles', this.addForm)
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.addDialogVisible = false
          this.$message.success(res.meta.msg)
          this.getRolesList()
        }
      })
    },
    rolesDeleted(id) {
      // 点击删除
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRolesList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    showEditDialog(data) {
      // 点击显示修改对话框并给输入框赋值
      this.editDialogVisible = true
      this.editForm.id = data.id
      this.editForm.roleName = data.roleName
      this.editForm.roleDesc = data.roleDesc
    },
    editRoles() {
      // 确认修改
      this.$refs.editForm.validate(async visible => {
        if (!visible) {
          this.$message.error('角色名称和描述内容不能为空 !')
        } else {
          const { data: res } = await this.$http.put(`roles/${this.editForm.id}`, this.editForm)
          console.log(res)
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }
          this.getRolesList()
          this.editDialogVisible = false
          this.$message.success(res.meta.msg)
        }
      })
    },
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 显示分配权限对话框
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      console.log(res)
      this.rightslist = res.data
      this.getLeafKeys(role, this.defkeys)
      this.setRightDialogVisible = true
    },
    getLeafKeys(node, arr) {
      // 通过递归的形式,获取角色下所有三级权限的id,并保存到数组defkeys
      if (!node.children) {
        // 如果node不包含children属性就是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    setRightDialogClose() {
      this.defkeys = []
    },
    async allotRights() {
      // 点击分配权限
      const keys = [
        ...this.$refs.treeref.getCheckedKeys(),
        ...this.$refs.treeref.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败!')
      }
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setRightDialogVisible = false
      console.log(keys)
    }
  }
}
</script>

<style scoped>
.el-table{
  margin-top: 15px;
}
.el-icon-caret-right{
  margin-left: 10px;
}
.el-row{
  margin: 0 !important;
}
.elRow{
  border: 1px solid #efefef;
  display: flex;
  align-items: center;
  margin: -1px 0 !important;
}
.el-col{
  padding: 0 !important;
}
.elRow1{
  padding: 5px 0;
  border-bottom: 1px solid #efefef;
  display: flex;
  align-items: center;
}
.elRow1:last-child{
  border-bottom: none;
}

.el-col-19{
  border-left: 1px solid #efefef;
}
.h-center {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}
.tag-lv3 {
   margin: 5px 10px 5px 0;
 }
</style>
